package com.wang.ddp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 全局ID生成器
 * @author wjh
 * @create 2023-04-21
 */
@Component
public class RedisIdWorker {

    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_SIZE = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * @param keyPrefix 业务前缀
     * @return
     */
    public long nextId(String keyPrefix){
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //当前时间减去2022-1-1 0:0:0的时间秒数
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        //生成序列号
        //构造key，key应该是icr:order:2023:04:21,这样子可以防止序列号在redis中自增爆满，因为每一天的序列号又会重新开始递增
        //而且还方便管理，想查某天的订单量也很方便
        //获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":"+date);
        //long类型8个字节 64位，而timeStamp一般4个字节，就拿现在2023-4-21时间减去2022-1-1 0:0:0时间秒数也就
        //41099940左右，而41099940转为二进制0010 0111 0011 0010 0010 1010 0100，32位不到，
        //那么前面四个字节就用0来补上，我们可以将timeStamp左移4个字节，也就是32位，后面4个字节32位来存储redis中的递增序列号
        //那么怎么将它们连接上呢，我们先将timeStamp左移32位，41099940左移32位也就是0010 0111 0011 0010 0010 1010 0100左移32位
        //0010 0111 0011 0010 0010 1010 0100 0000 0000 0000 0000 0000 0000 0000 0000，然后用按位或|运算符和redis递增序列号运算
        return timeStamp << COUNT_SIZE | increment;
    }

    public static void main(String[] args) {

        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //当前时间减去2022-1-1 0:0:0的时间秒数
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;

        System.out.println(timeStamp);
        System.out.println(timeStamp << COUNT_SIZE );
        System.out.println(timeStamp << COUNT_SIZE | 1L);
    }
}
